package run;

import sugges.Suggestion;
import base.*;
import java.io.*;
import java.util.ArrayList;

import java.awt.*;
import java.awt.event.*;

import javax.swing.*;
import javax.swing.border.Border;

public class CreateScreen extends JPanel {

	// DATA
	private Grid gridCreate;
	// **************GUI********************//

	private Box vertBox;
	private Box topBox;
	private Box clueBox;
	private Box boxButtons;
	private Box addButtons;

	private JList jList1 = new JList();
	private JScrollPane jScrollPane1 = new JScrollPane();
	private JTextPane clueTextPane = new JTextPane();

	private JButton btnAddWord = new JButton();
	private JButton btnDeleteWord = new JButton();
	private JButton btnSuggestWords = new JButton();
	private JButton btnWriteClue = new JButton();
	private JButton btnKeyWord = new JButton();
	private JRadioButton add1;
	private JRadioButton add2;

	private Border brdThinGrey = BorderFactory.createLineBorder(Color.gray, 1);
	private Border brdMedBlack = BorderFactory.createLineBorder(Color.BLACK, 2);
	private static int MARGIN_GAP = 5;
	// **************GUI********************//

	private int typeAdd;
	private boolean doSaveCheck = false;

	public CreateScreen() {
	}

	public CreateScreen(int width, int height) {

		Crossword cwCreate = new Crossword(width, height);
		gridCreate = new Grid(cwCreate);
		this.setLayout(new BorderLayout());
		displayGrid();
		try {
			jbInit();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		addListeners();

	}

	public void loadCrossword(JFrame jf) {
		JFileChooser chooser = new JFileChooser();
		chooser.showOpenDialog(jf);
		File f = chooser.getSelectedFile();

		ObjectInputStream ois = null;
		try {
			ois = new ObjectInputStream(new FileInputStream(f));
			Crossword cwCreate = (Crossword) ois.readObject();

			gridCreate = new Grid(cwCreate);
			this.setLayout(new BorderLayout());
			displayGrid();
			try {
				jbInit();
			} catch (Exception ex) {
				ex.printStackTrace();
			}
			addListeners();

			gridCreate.setCrossword(cwCreate);
			gridCreate.repopulateWords();
			validate();

			ois.close();
		} catch (Exception e) {
			System.out.print(e.getStackTrace());
		}
	}

	public boolean saveCrossword(JFrame jf) {
		Word w = gridCreate.getKey();
		if (w != null && gridCreate.checkKeyWord(w) == true) {
			gridCreate.getCrossword().setKey(w);
			JFileChooser chooser = new JFileChooser();
			chooser.showSaveDialog(jf);
			File f = chooser.getSelectedFile();

			ObjectOutputStream oos = null;
			try {
				oos = new ObjectOutputStream(new FileOutputStream(f));
				oos.writeObject(gridCreate.getCrossword());
				oos.close();
				doSaveCheck = false;
				return true;
			} catch (Exception e) {
				System.out.print(e.getStackTrace());
			}
		} else {
			JOptionPane
					.showMessageDialog(null, "Ô chữ có từ khóa không hợp lệ");
			return false;
		}
		return false;
	}

	public void setTheme(int i) {
		gridCreate.getCrossword().setTheme(i);
	}

	public int getTheme() {
		return gridCreate.getCrossword().getTheme();
	}

	public boolean getDoSaveCheck() {
		return doSaveCheck;
	}

	public void setDoSaveCheck(boolean b) {
		doSaveCheck = b;
	}

	public void setTime(int a, int b) {
		gridCreate.setTime(a, b);
	}

	@Override
	public void validate() {
		doSaveCheck = true;
		super.validate();
	}

	private void addListeners() {
		btnAddWord.addActionListener(new ButtonListener());
		btnDeleteWord.addActionListener(new ButtonListener());
		btnSuggestWords.addActionListener(new ButtonListener());
		btnWriteClue.addActionListener(new ButtonListener());
		btnKeyWord.addActionListener(new ButtonListener());
		add1.addActionListener(new RadioListener());
		add2.addActionListener(new RadioListener());

		jList1.addMouseListener(new ListListener());

		ArrayList squares = gridCreate.getSquares();
		for (int i = 0; i < squares.size(); i++) {
			Square s = (Square) squares.get(i);
			s.addMouseListener(new SquareListener());

		}
	}

	private void deleteWord() {
		if (gridCreate.getSelectedWord() == gridCreate.getPreviousWord()) {
			gridCreate.setPreivousWord(null);
		}
		gridCreate.deleteSelectedWord();
		doSaveCheck = true;
	}

	public void displayGrid() {
		gridCreate.Build();
		add(gridCreate, BorderLayout.CENTER);
	}

	private void setKeyword() {
		gridCreate.setKeyWord(true);
	}

	// tao cua so soan thao o chu

	private void jbInit() throws Exception {
		// ********** Khai báo*********//
		this.setBackground(new Color(174, 190, 212));

		vertBox = Box.createVerticalBox();
		topBox = Box.createHorizontalBox();
		clueBox = Box.createHorizontalBox();
		clueBox.setPreferredSize(new Dimension(100, 80));

		// gridCreate

		gridCreate.setPreferredSize(new Dimension(540, 510));
		gridCreate.addMouseListener(new ListListener());
		// list
		jList1.setMaximumSize(new Dimension(150, 500000));
		jList1.setMinimumSize(new Dimension(150, 300));
		jList1.setPreferredSize(new Dimension(150, 300000));
		jList1.setToolTipText("Match Key");
		jList1.setActionMap(null);
		jScrollPane1.setAutoscrolls(true);
		jScrollPane1.setMaximumSize(new Dimension(32767, 32767));
		jScrollPane1.setPreferredSize(new Dimension(150, 150));
		// clue
		clueTextPane.setBorder(brdMedBlack);
		clueTextPane.setEditable(false);
		clueTextPane.setFont(new Font("Arial", Font.CENTER_BASELINE, 20));
		clueTextPane.setText(gridCreate.getThemeName(gridCreate.getCrossword()));

		// button
		boxButtons = Box.createHorizontalBox();
		boxButtons.setBackground(new Color(199, 223, 236));
		addButtons = Box.createHorizontalBox();
		addButtons.setBackground(new Color(174, 190, 212));
		// add
		btnAddWord.setBorder(brdThinGrey);
		btnAddWord.setPreferredSize(new Dimension(100, 37));
		ImageIcon add = new ImageIcon(this.getClass().getResource(
				"/img/add.png"));
		btnAddWord.setIcon(add);
		btnAddWord.setToolTipText("Thêm từ mới");
		// typeadd
		add1 = new JRadioButton("Type");
		add1.setActionCommand("T");
		add1.setSelected(true);

		add2 = new JRadioButton("Draw");
		add1.setBackground(new Color(174, 190, 212));
		add2.setActionCommand("D");
		ButtonGroup btnTypeAdd = new ButtonGroup();
		add2.setBackground(new Color(174, 190, 212));
		btnTypeAdd.add(add1);
		btnTypeAdd.add(add2);
		JPanel panelTypeAdd = new JPanel(new GridLayout(0, 1));
		panelTypeAdd.add(add1);
		panelTypeAdd.add(add2);
		panelTypeAdd.setBorder(null);
		panelTypeAdd.setBackground(new Color(174, 190, 212));
		panelTypeAdd.setPreferredSize(new Dimension(60, 20));

		// delete
		btnDeleteWord.setBorder(brdThinGrey);
		btnDeleteWord.setPreferredSize(new Dimension(100, 37));
		ImageIcon del = new ImageIcon(this.getClass().getResource(
				"/img/del.png"));
		btnDeleteWord.setIcon(del);
		btnDeleteWord.setToolTipText("Xóa từ");

		// sugges
		btnSuggestWords.setBorder(brdThinGrey);
		btnSuggestWords.setPreferredSize(new Dimension(100, 37));
		ImageIcon find = new ImageIcon(this.getClass().getResource(
				"/img/find.png"));
		btnSuggestWords.setIcon(find);
		btnSuggestWords.setToolTipText("Tìm từ thích hợp");

		// clue
		btnWriteClue.setBorder(brdThinGrey);
		btnWriteClue.setPreferredSize(new Dimension(100, 37));
		ImageIcon clue = new ImageIcon(this.getClass().getResource(
				"/img/clue.png"));
		btnWriteClue.setIcon(clue);
		btnWriteClue.setToolTipText("Viết gợi ý");

		// key
		btnKeyWord.setBorder(brdThinGrey);
		btnKeyWord.setPreferredSize(new Dimension(100, 37));
		ImageIcon key = new ImageIcon(this.getClass().getResource(
				"/img/key.png"));
		btnKeyWord.setIcon(key);
		btnKeyWord.setToolTipText("Đánh dấu từ khóa");

		// **************** Vẽ GUI ***************//

		topBox.add(Box.createHorizontalStrut(MARGIN_GAP));
		topBox.add(gridCreate);

		topBox.add(Box.createHorizontalStrut(MARGIN_GAP));
		topBox.add(jScrollPane1);
		topBox.add(Box.createHorizontalStrut(MARGIN_GAP));

		vertBox.add(Box.createVerticalStrut(MARGIN_GAP));
		vertBox.add(topBox);
		vertBox.add(Box.createVerticalStrut(MARGIN_GAP));
		vertBox.add(clueBox);
		clueBox.add(Box.createHorizontalStrut(5));
		clueBox.add(clueTextPane);
		clueBox.add(Box.createHorizontalStrut(5));
		vertBox.add(Box.createVerticalStrut(10));
		vertBox.add(boxButtons);
		boxButtons.add(Box.createHorizontalStrut(20));
		boxButtons.add(panelTypeAdd);
		boxButtons.add(btnAddWord);
		boxButtons.add(Box.createHorizontalStrut(20));
		boxButtons.add(btnKeyWord);
		boxButtons.add(Box.createHorizontalStrut(20));
		boxButtons.add(btnDeleteWord);
		boxButtons.add(Box.createHorizontalStrut(20));
		boxButtons.add(btnSuggestWords);
		boxButtons.add(Box.createHorizontalStrut(20));
		boxButtons.add(btnWriteClue);
		boxButtons.add(Box.createHorizontalStrut(20));
		vertBox.add(Box.createVerticalStrut(MARGIN_GAP));
		add(vertBox, BorderLayout.CENTER);
	}

	class ButtonListener implements ActionListener {
		public void actionPerformed(ActionEvent e) {
			if (e.getSource().equals(btnAddWord)) {
				if (typeAdd == 2) {
					gridCreate.setDoSelectStart(true);
				} else {
					String[] option2 = { "Hàng ngang", "Hàng dọc",
							"Hàng chéo \\", "Hàng chéo /" };
					int temp = JOptionPane.showOptionDialog(null,
							"Chọn dạng từ muốn nhập", "Option Dialog",
							JOptionPane.DEFAULT_OPTION,
							JOptionPane.INFORMATION_MESSAGE, null, option2,
							option2[0]);
					if (temp >= 0 && temp <= 4)
						gridCreate.addWordType(temp);
				}
			} else if (e.getSource().equals(btnDeleteWord)) {
				deleteWord();
			} else if (e.getSource().equals(btnSuggestWords)) {
				Word w = gridCreate.getSelectedWord();
				ArrayList al = Suggestion.getMatches(w.getWord());
				jList1.setListData(al.toArray());
				jList1.setSelectedIndex(0);
				jScrollPane1.getVerticalScrollBar().setValue(0);
				jScrollPane1.getViewport().add(jList1);

			} else if (e.getSource().equals(btnWriteClue)) {
				gridCreate.writeClue();
			} else if (e.getSource().equals(btnKeyWord)) {
				if (gridCreate.getKeyWord() != true) {
                                    if (typeAdd == 2) {
					//gridCreate.setDoSelectStart(true);
                                        setKeyword();
				} else {
                                        gridCreate.setActiveKey(true);
					String[] option2 = { "Hàng ngang", "Hàng dọc",
							"Hàng chéo \\", "Hàng chéo /" };
					int temp = JOptionPane.showOptionDialog(null,
							"Chọn dạng từ muốn nhập", "Option Dialog",
							JOptionPane.DEFAULT_OPTION,
							JOptionPane.INFORMATION_MESSAGE, null, option2,
							option2[0]);
					if (temp >= 0 && temp <= 4)
						gridCreate.addWordType(temp);
                                        
				}
					
				} else {
					JOptionPane.showMessageDialog(null,
							"Không được nhập hai từ khóa");
				}
			}

		}
	}

	class RadioListener implements ActionListener {
		public void actionPerformed(ActionEvent e) {
			if (e.getActionCommand().equals("T")) {
				typeAdd = 1;
			} else if (e.getActionCommand().equals("D")) {
				typeAdd = 2;
			}
		}
	}

	// Xử lý sự kiện của con chuột
	class SquareListener implements MouseListener {
		public void mouseClicked(MouseEvent e) {
			Square sq = (Square) e.getSource();
			jScrollPane1.getViewport().remove(jList1);
			if (sq.getBackground() == Color.BLACK) {
				clueTextPane
						.setFont(new Font("Arial", Font.CENTER_BASELINE, 20));
				clueTextPane.setText(gridCreate.getThemeName(gridCreate
						.getCrossword()));
			} else {
				if (e.getClickCount() == 2) {
					Word w = gridCreate.getSelectedWord();
					if (w != null) {
						ArrayList al = Suggestion.getMatches(w.getWord());
						jList1.setListData(al.toArray());
						jList1.setSelectedIndex(0);
						jScrollPane1.getViewport().add(jList1);
						jScrollPane1.getVerticalScrollBar().setValue(0);
					}
				} else {
					clueTextPane.setFont(new Font("Arial",
							Font.CENTER_BASELINE, 16));
					clueTextPane.setText(gridCreate.getSelectedClue3());
				}
			}
		}

		public void mouseEntered(MouseEvent e) {
		}

		public void mouseExited(MouseEvent e) {
		}

		public void mousePressed(MouseEvent e) {
		}

		public void mouseReleased(MouseEvent e) {
		}

	}

	class ListListener implements MouseListener {
		public void mouseClicked(MouseEvent e) {
			Word w = gridCreate.getSelectedWord();
			if (e.getClickCount() == 2 && w != null) {
				String s = (String) jList1.getSelectedValue();
				if (!gridCreate.checkWordDuplicate(s)) {
					w.setWord(s);
					gridCreate.repopulateWords();

					if (w.getWordDirection() == Word.ACROSS) {

						for (int i = w.getX(); i < w.getX() + w.getLength(); i++) {
							Square sq = gridCreate.findSquare(w.getY(), i);
							if (sq.getWordDown() != null) {
								sq.getWordDown().addLetter(sq.getLetter(),
										sq.getLetterIndexDown());
							}
						}
					}

					if (w.getWordDirection() == Word.DOWN) {

						for (int i = w.getY(); i < w.getY() + w.getLength(); i++) {
							Square sq = gridCreate.findSquare(i, w.getX());
							if (sq.getWordAcross() != null) {
								sq.getWordAcross().addLetter(sq.getLetter(),
										sq.getLetterIndexAcross());
							}
						}
					}
					if (w.getWordDirection() == Word.BIAS1) {

						for (int i = 0; i < w.getLength(); i++) {
							Square sq = gridCreate.findSquare(w.getY() + i, w
									.getX()
									+ i);
							if (sq.getWordAcross() != null) {
								sq.getWordAcross().addLetter(sq.getLetter(),
										sq.getLetterIndexBias1());
							}
						}
					}
					if (w.getWordDirection() == Word.BIAS2) {
						for (int i = 0; i < w.getLength(); i++) {
							Square sq = gridCreate.findSquare(w.getY() - i, w
									.getX()
									+ i);
							if (sq.getWordAcross() != null) {
								sq.getWordAcross().addLetter(sq.getLetter(),
										sq.getLetterIndexBias2());
							}
						}
					}
				} else
					JOptionPane.showMessageDialog(null, s.toUpperCase()
							+ " trùng với từ đã có");
			}
		}

		public void mouseEntered(MouseEvent e) {
		}

		public void mouseExited(MouseEvent e) {
		}

		public void mousePressed(MouseEvent e) {
		}

		public void mouseReleased(MouseEvent e) {
		}
	}

}
